package com.czk.security.interceptor;

import com.czk.security.model.UserDto;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 拦截器
 *
 * @Author:ChenZhangKun
 * @Date: 2021/3/19 9:34
 */
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 校验用户请求的url是否在用户的权限列表内
        // 取出用户的身份信息
        Object attribute = request.getSession().getAttribute(UserDto.SESSION_USER_KEY);
        if (attribute == null) {
            writeContent(response, "请登录");
        }
        UserDto userDto = (UserDto) attribute;
        // 拿到权限
        String requestURI = request.getRequestURI();
        if (userDto.getAuthorities().contains("p1") && requestURI.contains("/r/r1")) {
            // 有权限访问
            return true;
        }
        if (userDto.getAuthorities().contains("p2") && requestURI.contains("/r/r2")) {
            // 有权限访问
            return true;
        }
        writeContent(response, "没有权限访问");
        return false;
    }

    /**
     * 输出内容
     *
     * @param response
     * @param content
     * @throws IOException
     */
    private void writeContent(HttpServletResponse response, String content) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println(content);
        writer.close();
        response.resetBuffer();
    }
}
